<template>
  <div class="emp-info">
    <!-- 编辑模式 -->
    <div class="emp-info-edit">
      <div class="emp-info-header">
        <div class="emp-info-actions">
          <el-button @click="handleCancelEdit">返回</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving"
            >保存</el-button
          >
        </div>
      </div>

      <div class="form-sections">
        <!-- 基础信息 -->
        <div class="form-section">
          <div style="display: flex">
            <div class="section-box"></div>
            <div class="section-title">基础信息</div>
          </div>
          <PageForm
            v-if="deptList.length > 0"
            ref="editFormRef"
            :form-data="formData"
            :list="editBasicInfoFormList"
            :rules="formRules"
          >
            <template #deptId>
              <el-select
                v-model="formData.deptId"
                filterable
                clearable
                class="m-2"
                placeholder="科室"
                style="width: 400px"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </PageForm>
        </div>

        <!-- 角色与权限 -->
        <div class="form-section">
          <div style="display: flex">
            <div class="section-box"></div>
            <div class="section-title">角色与权限</div>
          </div>
          <PageForm
            ref="editFormRef2"
            :form-data="formData"
            :list="editRolePermissionFormList"
            :rules="formRules"
          >
            <template #roleIdList>
              <el-select
                v-model="formData.roleIdList"
                filterable
                :multiple="true"
                class="m-2"
                placeholder="角色"
                style="width: 400px"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </PageForm>
        </div>

        <!-- 个人信息 -->
        <div class="form-section">
          <div style="display: flex">
            <div class="section-box"></div>
            <div class="section-title">个人信息</div>
          </div>
          <PageForm
            ref="editFormRef3"
            :form-data="formData"
            :list="editPersonalInfoFormList"
            :rules="formRules"
          />
          <el-button
            style="margin-left: 120px"
            type="primary"
            @click="handleSave"
            :loading="saving"
            >保存</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import type { Employee, EmployeeForm } from '@/types/employee';
import type { PageFormList } from '@/types/PageForm';
import type { FormRules } from 'element-plus';
import { addEmployee, editEmployee } from '@/api/clinic/index';
import { deptGetSelectList } from '@/api/account';
import { getRoleList, getEmpDetail } from '@/api/clinic/index';
import { uploadFile } from '@/api/basedata';
import { parseBirthFromIdCard, solarToLunarString } from '@/utils/lunar';
import stores from '@/store';
const useBaseDataStore = stores.useBaseDataStore();
definePageMeta({
  name: '用户详情',
});
const deptList = ref<any[]>([]);

const deptGetSelectListApi = async () => {
  let res = await deptGetSelectList();
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  res.data.forEach((item: any) => {
    item.label = item.deptName;
    item.value = item.deptId;
  });
  deptList.value = res.data;
  //console.log(deptList.value);
};
deptGetSelectListApi();

const roleList = ref<any[]>([]);
const getRoleListApi = async () => {
  let res = await getRoleList({ pageNo: 1, pageSize: 999999 });
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  res.data.list.forEach((item: any) => {
    item.label = item.roleName;
    item.value = item.roleId;
  });
  roleList.value = res.data.list;
};
getRoleListApi();

// Emits
const emit = defineEmits<{
  close: [];
  save: [data: EmployeeForm];
}>();

// 响应式数据
const isEdit = ref(false);
const saving = ref(false);
const detailFormRef = ref();
const editFormRef = ref();
const editFormRef2 = ref();
const editFormRef3 = ref();

// 表单数据
const formData = ref<any>({
  roleIdList: [],
  avatarUrl: '',
  empName: '',
  phone: '',
  deptId: '',
  title: '',
  gender: '1',
  idCard: '',
  empNo: '',
  solarBirthday: '',
  lunarBirthday: '',
  hireDate: '',
  cardNo: '',
  email: '',
  nativeProvince: '',
  nativeCity: '',
  nativeCounty: '',
  homeProvince: '',
  homeCity: '',
  homeCounty: '',
  homeAddress: '',
});
// 当身份证号变化时，自动解析出生日期，填充阳历/阴历生日
watch(
  () => formData.value.idCard,
  (id) => {
    const s = (id || '').trim();
    // 为空时清空
    if (!s) {
      formData.value.solarBirthday = '';
      formData.value.lunarBirthday = '';
      return;
    }

    // 仅在长度达到 15 或 18 位时再解析，避免输入中途误清空
    if (s.length === 15 || s.length === 18) {
      const solar = parseBirthFromIdCard(s);
      if (solar) {
        formData.value.solarBirthday = solar;
        formData.value.lunarBirthday = solarToLunarString(solar);
      }
      // 如果长度达标但解析失败，不强制清空，保留用户可能手动选择的生日
    }
  },
  { immediate: true }
);
//数据
const route = useRoute();
if (route.query.empId) {
  // let empInfo:any =  sessionStorage.getItem('empInfo');
  let res: any = await getEmpDetail({ empId: route.query.empId });
  if(res.code != '200'){
    //ElMessage.error(res.msg);
  }else{
     let list: any = [];
    res.data.roleList.forEach((item: any) => {
      list.push(item.roleId);
    });
    res.data.roleIdList = list;

    let empInfo: any = res.data;
    if (empInfo) {
      if (route.query.empId == empInfo?.empId) {
        // formData.value = empInfo;

        //console.log(empInfo);

        formData.value = {
          empId: empInfo.empId,
          roleIdList: empInfo.roleIdList || [],
          avatarUrl: empInfo.avatarUrl || '',
          empName: empInfo.empName || '',
          phone: empInfo.phone || '',
          empNo: empInfo.empNo || '',
          deptId: empInfo.deptId || '',
          title: empInfo.title || '',
          gender: empInfo.gender || '1',
          idCard: empInfo.idCard || '',
          solarBirthday: empInfo.solarBirthday || '',
          lunarBirthday: empInfo.lunarBirthday || '',
          hireDate: empInfo.hireDate || '',
          cardNo: empInfo.cardNo || '',
          email: empInfo.email || '',
          nativeProvince: empInfo.nativeProvince || '',
          nativeCity: empInfo.nativeCity || '',
          nativeCounty: empInfo.nativeCounty || '',
          homeProvince: empInfo.homeProvince || '',
          homeCity: empInfo.homeCity || '',
          homeCounty: empInfo.homeCounty || '',
          homeAddress: empInfo.homeAddress || '',
          titleUrl: empInfo.titleUrl || '',
          jg: [
            Number(empInfo.nativeProvince),
            Number(empInfo.nativeCity),
            Number(empInfo.nativeCounty),
          ],
          jtzz: [
            Number(empInfo.homeProvince),
            Number(empInfo.homeCity),
            Number(empInfo.homeCounty),
          ],
        };
      }
    }
  }
 
}

// 编辑模式 - 基础信息表单配置
const editBasicInfoFormList: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '头像',
        prop: 'avatarUrl',
        component: 'imgUpload',
        beforeUpload(file: { name: string }) {
          //console.log(file);
          uploadFile(file, file.name).then((res) => {
            if(res.code != '200'){
              //ElMessage.error(res.msg);
              return
            }else{
              ElMessage.success('上传成功');
              formData.value.avatarUrl = res.data;
              //console.log(formData.value.avatarUrl);
            }
          
          });
          return false; // 阻止自动上传
        },
      },
      {
        span: 24,
        label: '姓名',
        prop: 'empName',
        component: 'input',
        componentProps: {
          width: '400px',

          placeholder: '请输入姓名',
        },
      },
      {
        span: 24,
        label: '电话',
        prop: 'phone',
        component: 'input',
        componentProps: {
          width: '400px',

          placeholder: '请输入电话',
        },
      },
      {
        span: 24,
        label: '所属科室',
        prop: 'deptId',
        componentProps: {
          width: '400px',
          slotName: 'deptId',
          placeholder: '所属科室',
        },
        labelWidth: '130px',
        component: 'slotName',
      },
      {
        span: 24,
        label: '职称',
        prop: 'title',
        component: 'input',
        componentProps: {
          width: '400px',

          placeholder: '请输入职称',
        },
      },
      {
        span: 24,
        label: '工号',
        prop: 'empNo',
        component: 'input',
        disabled: true,
        componentProps: {
          width: '400px',

          placeholder: '创建后自动生成',
        },
      },
    ],
  },
];

// 编辑模式 - 角色与权限表单配置
const editRolePermissionFormList: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '角色',
        prop: 'roleIdList',
        componentProps: {
          width: '400px',
          slotName: 'roleIdList',
          placeholder: '角色',
        },
        labelWidth: '130px',
        component: 'slotName',
      },
    ],
  },
];

// 编辑模式 - 个人信息表单配置
const editPersonalInfoFormList: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '身份证号',
        prop: 'idCard',
        component: 'input',
        componentProps: {
          placeholder: '请输入身份证号',
          width: '400px',
        },
      },
      {
        span: 24,
        label: '性别',
        prop: 'gender',
        component: 'select',
        componentProps: {
          placeholder: '请选择性别',
          width: '400',
        },
        // selectGroupOptions: [
        //   { label: '男', value: '1' },
        //   { label: '女', value: '0' },
        // ],
        get selectGroupOptions() {
          const data = useBaseDataStore.getEnumSelect('genderEnum');
          const data1 = data.map((item: any) => ({
            label: item.text,
            value: item.value.toString(),
          }));
          return data1
        },
      },
    ],
  },
  {
    list: [
      {
        span: 24,
        label: '阳历生日',
        prop: 'solarBirthday',
        component: 'date',
        componentProps: {
          placeholder: '请选择阳历生日',
          width: '400',
        },
      },
      {
        span: 24,
        label: '阴历生日',
        prop: 'lunarBirthday',
        component: 'date',
        componentProps: {
          width: '400',

          placeholder: '请选择阴历生日',
        },
      },
    ],
  },
  {
    list: [
      {
        span: 24,
        label: '入职日期',
        prop: 'hireDate',
        component: 'date',
        componentProps: {
          width: '400',
          placeholder: '请选择入职日期',
        },
      },
      {
        span: 24,
        label: '工资卡号',
        prop: 'cardNo',
        component: 'input',
        componentProps: {
          width: '400px',
          placeholder: '请输入工资卡号',
        },
      },
    ],
  },

  {
    list: [
      {
        span: 24,
        label: '邮箱',
        prop: 'email',
        component: 'input',
        componentProps: {
          placeholder: '请输入邮箱',
          width: '400px',
        },
      },
      {
        span: 24,
        label: '籍贯',
        prop: 'jg',
        component: 'cascader',
        cascaderProps: {
          value: 'code',
          label: 'name',
          children: 'children',
        },
        componentProps: {
          placeholder: '请输选择籍贯',
          width: '400px',
        },
        onChange: (value: string[]) => {
          //console.log('选择的地区代码:', value);
          formData.value.nativeProvince = value[0];
          formData.value.nativeCity = value[1];
          formData.value.nativeCounty = value[2];
        },
      },
    ],
  },
  {
    list: [
      {
        span: 8,
        label: '家庭住址',
        prop: 'jtzz',
        component: 'cascader',
        cascaderProps: {
          value: 'code',
          label: 'name',
          children: 'children',
        },
        componentProps: {
          placeholder: '请输选择家庭住址',
          width: '400px',
        },
        onChange: (value: string[]) => {
          //console.log('选择的地区代码:', value);
          formData.value.homeProvince = value[0];
          formData.value.homeCity = value[1];
          formData.value.homeCounty = value[2];
        },
      },
      {
        span: 12,
        label: '',
        prop: 'homeAddress',
        component: 'input',
        labelWidth: '1px',
        componentProps: {
          width: '400px',
          placeholder: '详细地址',
        },
      },
      {
        span: 24,
        label: '职业资格',
        prop: 'titleUrl',
        component: 'imgUpload',
        beforeUpload(file: { name: string }) {
          //console.log(file);
          uploadFile(file, file.name).then((res) => {
           if(res.code != '200'){
              //ElMessage.error(res.msg);
              return
            }else{
              ElMessage.success('上传成功');
              formData.value.titleUrl = res.data;
            }
          });
          return false; // 阻止自动上传
        },
      },
    ],
  },
];

// 表单验证规则
const formRules: FormRules = {
  empName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '员工姓名长度为2-20个字符', trigger: 'blur' },
  ],
  // empNo: [
  //   { required: true, message: '请输入工号', trigger: 'blur' },
  //   { min: 3, max: 20, message: '工号长度为3-20个字符', trigger: 'blur' },
  // ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  deptId: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
  roleIdList: [{ required: true, message: '请选择角色', trigger: 'change' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  isEnabled: [{ required: true, message: '请选择在职状态', trigger: 'change' }],
  isAdmin: [{ required: true, message: '请选择是否管理员', trigger: 'change' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
     
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号',
      trigger: 'blur',
    },
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  hireDate: [{  required: true,  message: '请选择入职日期', trigger: 'change' }],
};

// 编辑操作
const handleEdit = () => {
  isEdit.value = true;
};

// 取消编辑
const handleCancelEdit = () => {
  navigateTo(
    '/manage/managePages/clinic?menuId=' +
      route.query.menuId +
      '&' +
      'submenuId=' +
      route.query.submenuId +
      '&tab=manage-clinic-emp'
  );
};

// 保存操作
const handleSave = async () => {
  if (!editFormRef.value || !editFormRef2.value || !editFormRef3.value) return;

  try {
    // 表单验证 - 验证所有分组表单
    let a =   await editFormRef.value.ruleFormRef.validate();
    let b =   await editFormRef2.value.ruleFormRef.validate();
    let c =   await editFormRef3.value.ruleFormRef.validate();
    //console.log(a, b, c);
    if(a==true && b==true && c == true){
      if (!formData.value.empId) {
      let data = {
        ...formData.value,
      };
      delete data.jg;
      delete data.jtzz;
      let res = await addEmployee(data);
      if (res.code === '200') {
        ElMessage.success('保存成功');
        navigateTo(
          '/manage/managePages/clinic?menuId=' +
            route.query.menuId +
            '&' +
            'submenuId=' +
            route.query.submenuId +
            '&tab=manage-clinic-emp'
        );
      } else {
        //ElMessage.error(res.msg);
      }
    } else {
      let data = {
        ...formData.value,
      };
      delete data.jg;
      delete data.jtzz;
      let res = await editEmployee(data);
      if (res.code === '200') {
        ElMessage.success('保存成功');
        navigateTo(
          '/manage/managePages/clinic?menuId=' +
            route.query.menuId +
            '&submenuId=' +
            route.query.submenuId +
            '&tab=manage-clinic-emp'
        );
      } else {
        //ElMessage.error(res.msg);
      }
    }
    }
    // saving.value = true;

    
  } catch (error) {
    //console.error('保存失败:', error);
    //ElMessage.error('保存失败，请检查表单信息');
  } finally {
    saving.value = false;
  }
};
</script>

<style lang="scss" scoped>
.emp-info {
  height: 100%;
  display: flex;
  flex-direction: column;

  .emp-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0 20px 0;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .emp-info-actions {
      display: flex;
      justify-content: space-between;
      width: 100%;
    }
  }

  .emp-info-detail,
  .emp-info-edit {
    flex: 1;
    overflow-y: auto;
    padding: 26px 20px;
  }

  .form-sections {
    .form-section {
      margin-bottom: 30px;

      &:last-child {
        margin-bottom: 0;
      }
      .section-box {
        width: 4px;
        height: 16px;
        background: var(--el-color-primary);
        margin-top: 4px;
      }
      .section-title {
        font-size: 16px;
        font-weight: 600;
        width: 100%;
        color: #303133;
        margin-bottom: 16px;
        padding-bottom: 8px;
        padding-left: 7px;
        border-bottom: 1px solid #e7e7e7;
        position: relative;
      }
    }
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;

    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }

    .el-input,
    .el-select,
    .el-input-number {
      width: 100%;
    }

    .el-textarea {
      .el-textarea__inner {
        resize: vertical;
      }
    }
  }
}
</style>
